<template>
  <div class="infobox">
    <div class="topbox">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-button type="primary" @click="addbutton">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="danzibox" v-for="(item, indexone) in datalist" :key="indexone">
      <div class="newtopbt">
        <el-button type="primary" @click="deletebutton(item.id)">删除</el-button>
        <el-button type="primary" @click="xgbutton(item.id)">修改</el-button>
      </div>
      <div class="hydbox">
        <span>化验单照片:</span>
        <el-image class="imgbox" :src="item.photoUrl" @click="seeimg(item.photoUrl)" />
      </div>
      <div class="hydbox">
        <span>化验时间:</span>
        <div>{{ item.testTime }}</div>
      </div>

      <div class="hydbox">
        <span>单位:</span>
        <div>{{ item.testHospital }}</div>
      </div>

      <div class="hydbox">
        <span>记录人:</span>
        <div>{{ item.createBy }}</div>
      </div>

      <div v-for="(itemtwo, indextwo) in item.items" :key="indextwo">
        <div class="hydbox btclass">
          <span>检查项:</span>
          <div>
            {{ itemtwo.itemName }}
          </div>
        </div>
        <div>
          <el-table :data="itemtwo.list" border style="width: 100%">
            <el-table-column prop="codeName" label="项目" />
            <el-table-column label="结果" prop="result"> </el-table-column>
            <el-table-column label="状态" width="120" prop="statusName"> </el-table-column>
            <el-table-column label="单位" width="120" prop="unit"> </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- <div v-if="datalist.length > 0">
      <div v-for="(item, indexone) in datalist" :key="indexone" class="huxmlist">
        <div class="onedabg">
          <div class="hxtyopname" v-if="indexone === 0">化验单照片</div>
          <div class="hyxvalue">
            <el-image style="width: 100px; height: 50px" :src="item.photoUrl" @click="seeimg(item.photoUrl)" />
          </div>
        </div>

        <div class="xiaobaioge">
          <div v-for="(itemtwo, indextwo) in item.items" :key="indextwo" class="ztbioge">
            <div class="jcxitems">
              <div class="jcxnametop" v-if="indexone === 0 && indextwo === 0">检查项</div>
              <div class="jcxvalue">{{ itemtwo.itemName }}</div>
            </div>

            <el-table
              :data="itemtwo.list"
              border
              style="width: 600px"
              @selection-change="handleSelectionChange"
              :show-header="indexone === 0 && indextwo === 0"
            >
              <el-table-column prop="codeName" align="center" width="200px" label="项目" />

              <el-table-column prop="result" align="center" label="结果" />
              <el-table-column prop="statusName" align="center" label="状态" />
              <el-table-column prop="unit" align="center" label="单位" />
            </el-table>

            <div class="jcxitemsthree">
              <div class="jcxnametopthree" v-if="indexone === 0 && indextwo === 0">化验时间</div>
              <div class="jcxvaluethree">{{ item.testTime }}</div>
            </div>
            <div class="jcxitemsthree">
              <div class="jcxnametopthree" v-if="indexone === 0 && indextwo === 0">单位</div>
              <div class="jcxvaluethree">{{ item.testHospital }}</div>
            </div>
            <div class="jcxitemsthree">
              <div class="jcxnametopthree" v-if="indexone === 0 && indextwo === 0">记录人</div>
              <div class="jcxvaluethree">{{ item.createBy }}</div>
            </div>
          </div>
        </div>
        <div class="jcxitemsthree">
          <div class="jcxnametopthree" v-if="indexone === 0">操作</div>
          <div class="jcxvaluethree">
            <span class="scbuttons scbuts" @click="deletebutton(item.id)">删除</span>
            <span class="scbuttons" @click="xgbutton(item.id)">修改</span>
          </div>
        </div>
      </div>
    </div> -->
    <!-- <div v-else class="zusjclass">暂无数据</div> -->

    <el-dialog v-model="dialogVisible" title="化验单详情" width="800" :before-close="handleClose">
      <el-form :model="formlist" label-width="auto" style="max-width: 700px">
        <el-form-item label="化验照片">
          <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            multiple
            :limit="1"
            :http-request="uploadFile"
            :on-preview="handlePreview"
          >
            <el-button type="primary">上传图片</el-button>
            <template #tip>
              <div class="el-upload__tip"></div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="化验时间">
          <el-date-picker v-model="formlist.testTime" value-format="YYYY-MM-DD" type="date" style="width: 240px" />
        </el-form-item>
        <el-form-item label="化验医院">
          <el-input v-model="formlist.testHospital" />
        </el-form-item>

        <el-form-item label="化验项目">
          <el-select v-model="formlist.hyxm" multiple placeholder="  " style="width: 100%" @change="hyxulist">
            <el-option v-for="item in hyxmlist" :key="item.value" :label="item.label" :value="item.label" />
          </el-select>
        </el-form-item>

        <div class="wclistbox">
          <div v-for="(item, index) in tableData" :key="index" class="huxmlist">
            <div class="leftbg">
              <div class="titlesbox">化验项</div>
              <div class="namsitens">{{ item.itemName }}</div>
            </div>

            <el-table :data="item.list" border style="width: 100%">
              <el-table-column prop="codeName" label="项目" />
              <el-table-column label="结果">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <el-input v-model="scope.row.result"></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="120">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <el-select v-model="scope.row.statusName" placeholder="" size="large" style="width: 240px">
                      <el-option
                        v-for="item in scope.row.dictList"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                      />
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="单位" width="120">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <el-input v-model="scope.row.unit"></el-input>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savebutton"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { pLhyaddApi, updatehyjlApi, addhydApi, dehyjlApi, getListBylabTestItemId, uploadAPI } from "@/api/hzmange/index.js";
import { seekdataApi } from "@/api/system/system.js";
import { useRoute } from "vue-router";
let formlist = ref({});
const route = useRoute();
const useInfo = JSON.parse(sessionStorage.getItem("useInfo"));
const routedata = reactive(route.query);
const dialogVisible = ref(false);
let dialogVisibletwo = ref(false);

let imgList = ref("");
let addxllist = ref([]);
const fileList = ref([]);
let formInline = ref({
  pageNum: 1,
  pageSize: 10
});
let xgstatus = ref(false);
let datalist = ref([]);
var pagetotal = ref(0);
const tableData = ref([]);
let addbutton = () => {
  newhuixianlist.value = [];

  xgstatus.value = true;
  formlist.value = {
    pageNum: 1,
    pageSize: 10,
    patientName: "",
    testHospital: "山东大学齐鲁医院"
  };
  fileList.value = [];
  tableData.value = [];
  xgstatus.value = false;
  dialogVisible.value = true;
};
let selection = ref([]);
const handleSelectionChange = e => {
  selection.value = e;
};
const handleClose = () => {
  dialogVisible.value = false;
};
const handleClosetwo = () => {
  dialogVisibletwo.value = false;
};

let uploadFile = val => {
  const fd = new FormData();
  fd.append("file", val.file);
  uploadAPI(fd).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "上传成功",
        type: "success"
      });
      imgList.value = res.url;
      formlist.value.photoUrl = res.url;
    } else {
      ElMessage({
        message: res.msg,
        type: "error"
      });
    }
  });
};
let savebutton = () => {
  let addparam = {
    patientName: routedata.name, //患者姓名
    patientId: routedata.id, //患者ID
    testTime: formlist.value.testTime, //化验时间
    testHospital: formlist.value.testHospital, //化验医院
    photoUrl: formlist.value.photoUrl, //化验单照片URL
    items: tableData.value
  };

  //修改
  if (xgstatus.value == true) {
    addparam.id = xgid.value;

    updatehyjlApi(addparam).then(() => {
      ElMessage({
        message: "修改成功",
        type: "success"
      });

      dialogVisible.value = false;
      xgstatus.value = false;
      //刷新列表数据
      getList();
    });
  } else {
    //新增
    addhydApi(addparam).then(() => {
      ElMessage({
        message: "新增成功",
        type: "success"
      });
      dialogVisible.value = false;
      getList();
    });
  }
};

const spanArr = ref([]);
const pos = ref(0);
const getSpanArr = data => {
  spanArr.value = [];
  for (let i = 0; i < data.length; i++) {
    if (i === 0) {
      spanArr.value.push(1);
      pos.value = 0;
    } else {
      // 判断当前元素与上一个元素是否相同
      if (data[i].itemName === data[i - 1].itemName) {
        spanArr.value[pos.value] += 1;
        spanArr.value.push(0);
      } else {
        spanArr.value.push(1);
        pos.value = i;
      }
    }
  }
};

// 合并方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    const _row = spanArr.value[rowIndex];
    const _col = _row > 0 ? 1 : 0;
    return {
      rowspan: _row,
      colspan: _col
    };
  }
};
var tablelist = [];
//下拉化验项目单子,选出对用的项目
let hyxulist = e => {
  let YPlist = JSON.parse(sessionStorage.getItem("YPlist"));
  let checkdata = e.flatMap(key => YPlist[key] || []);

  let nealsit = tableData.value;

  const mapA = new Map(nealsit.map(item => [item.itemCode, item]));

  // 使用map方法遍历b，并用a中的对象替换
  let result = checkdata.map(itemB => {
    // 查找是否有匹配的itemCode
    const matchedItem = mapA.get(itemB.itemCode);
    // 如果找到匹配项，则使用a中的完整对象，否则保留原来的对象
    return matchedItem ? matchedItem : itemB;
  });
  tableData.value = result;
};

let handleSizeChange = () => {
  formInline.value.pageNum = 1;
  getList();
};
let handleCurrentChange = () => {
  getList();
};
// 初始化数据
getList();
function flattenData(data) {
  const result = [];
  let aaa = [
    {
      id: 1,
      date: "2016-05-03",
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles"
    },
    {
      id: 1,
      date: "2016-05-03",
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles"
    },
    {
      id: 2,
      date: "2016-05-04",
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles"
    },
    {
      id: 2,
      date: "2016-05-0",
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles"
    }
  ];

  data.forEach(record => {
    record.items.forEach(item => {
      console.log("111111111111111111", item);
      item.list.forEach(detail => {
        result.push({
          id: record.id,
          photoUrl: record.photoUrl, //化验单图片
          testTime: record.testTime, //化验时间
          testHospital: record.testHospital, //单位
          createBy: record.createBy, //记录人
          itemName: item.itemName, // 检查项名称
          codeName: detail.codeName, //项目
          result: detail.result, //结果
          statusName: detail.statusName, //状态
          unit: detail.unit //单位
        });
      });
    });
  });

  return result;
}
// 获取数据
function getList() {
  pLhyaddApi({ patientId: routedata.id }).then(res => {
    datalist.value = res.data;
    console.log("后来的", datalist.value);
    // pagetotal.value = res.total;
  });
}

getYZlsit();
let hyxmlist = ref([]);
let yylist = ref([]);
function getYZlsit() {
  seekdataApi({ dictType: "sys_laboratory_item" }).then(res => {
    hyxmlist.value = res.data.map(item => ({
      value: item.dictValue,
      label: item.dictLabel
    }));
  });

  seekdataApi({ dictType: "sys_hospital_name" }).then(res => {
    yylist.value = res.data.map(item => ({
      value: item.dictValue,
      label: item.dictLabel
    }));
  });

  seekdataApi({ dictType: "sys_laboratory_status_" }).then(res => {
    addxllist.value = res.data.map(item => ({
      value: item.dictValue,
      label: item.dictLabel
    }));
  });
}
var xgid = ref(0);
let newhuixianlist = ref([]);

//修改
const xgbutton = eid => {
  xgstatus.value = true;
  getListBylabTestItemId({
    id: eid
  }).then(res => {
    formlist.value = res.data; //表单数据
    //修改值
    let yzlsit = [];
    res.data.items.forEach(item => {
      yzlsit.push(item.itemName);
    });
    formlist.value.hyxm = yzlsit; //化验项目
    newhuixianlist.value = yzlsit; //化验项目

    xgid.value = res.data.id; //修改id
    tableData.value = res.data.items; //table数据
    // getSpanArr(tableData.value);
    let urlname = res.data.photoUrl;
    if (urlname) {
      fileList.value = [
        {
          name: urlname.substring(urlname.lastIndexOf("/") + 1),
          url: res.data.photoUrl
        }
      ]; //附件数据
    }

    dialogVisible.value = true;
    setTimeout(() => {
      xgstatus.value = true;
    }, 100);
  });
};
const deletebutton = id => {
  ElMessageBox.confirm("确定删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    dehyjlApi({
      id: id
    }).then(res => {
      ElMessage({
        type: "success",
        message: `${res.msg}`
      });
      getList();
    });
  });
};
async function handlePreview(e) {
  const url = e.url; // 文件的URL
  try {
    const response = await fetch(url);
    const blob = await response.blob();
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = e.name.substring(e.name.lastIndexOf("/") + 1); // 获取文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(link.href); // 清除创建的对象URL以释放内存
  } catch (error) {
    console.error("下载文件时出错:", error);
  }
}
let seeimg = e => {
  window.open(e, "_blank", "noopener,noreferrer");
};
</script>

<style lang="scss" scoped>
.topbox {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 10px;
}
.tableboxs {
  height: 500px;
  overflow: auto;
}

.hydbox {
  display: flex;
  align-items: center;
}
.infobox {
  height: 650px;
  overflow: auto;
}
.fybox {
  display: flex;
  justify-content: end;
}
.wclistbox {
  height: 300px;
  overflow: auto;
}
.wclistboxtwo {
  height: 500px;
  overflow: auto;
}
.huxmlist {
  display: flex;
}
.leftbg {
}
.titlesbox {
  width: 50px;
  color: #909399;
  font-weight: bold;
  border-top: 1px solid #ebeef5;
  height: 37px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
}
.namsitens {
  height: 100%;
  display: flex;
  align-items: center;
  color: #909399;
  font-weight: bold;
}
.seekxq {
  color: #009688;
  cursor: pointer;
}
.xiaobaioge {
  display: flex;
  flex-direction: column;
  border-bottom: 1px solid #ebeef5;
}
.ztbioge {
  display: flex;
}
.jcxitems {
  width: 150px;
}

.jcxvalue {
  width: 150px;
  height: calc(100% - 37px);
  display: flex;
  align-items: center;
  color: #606266;

  justify-content: center;

  border-right: 1px solid #ebeef5;
  font-size: 12px;
}
.jcxitemsthree {
  width: 120px;
  border-bottom: 1px solid #ebeef5;
}
.jcxvaluethree {
  width: 120px;
  height: calc(100% - 37px);
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 12px;
  justify-content: center;
  // border-bottom: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
  align-items: center;
  border-right: #ebeef5 1px solid;
  color: #606266;
}
.jcxnametopthree {
  width: 120px;
  color: #909399;
  border-top: 1px solid #ebeef5;
  height: 37px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #ebeef5;
  font-size: 14px;
  color: #606266;
}
.onedabg {
  // background: red;
  border-right: 1px solid #ebeef5;
  border-left: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}
.jcxnametop {
  width: 150px;
  color: #909399;
  font-weight: bold;
  border-top: 1px solid #ebeef5;
  height: 37px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  font-size: 14px;
  justify-content: center;
}

.hxtyopname {
  width: 100px;
  color: #909399;
  font-weight: bold;
  border-top: 1px solid #ebeef5;
  height: 37px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  font-size: 14px;
  justify-content: center;
}
.hyxvalue {
  height: 100%;
  display: flex;
  align-items: center;
  color: #909399;
  font-weight: bold;
  // border-bottom: 1px solid #ebeef5;
}
.scbuts {
  margin-right: 10px;
}
.scbuttons {
  color: #009688;

  cursor: pointer;
}
.zusjclass {
  color: #000;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
}
.danzibox {
  border: 1px dashed #009688;
  color: #606266;
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 20px;
}
.hydbox {
  display: flex;
  align-items: center;
  margin: 10px;
}
.imgbox {
  width: 80px;
  height: 50px;
  margin-left: 10px;
  cursor: pointer;
}
.jcxbox {
  display: flex;
  justify-content: space-between;
}
.jcxbox .el-input {
  width: 150px;
}
.btclass {
  color: #009688;
}
.newtopbt {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin: 10px;
  float: right;
}
</style>
